package org.gwtEss.client.messages;

import org.gwtEss.table.TextDesc;

import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.DecoratedPopupPanel;
import com.google.gwt.user.client.ui.HTML;

public class FlashMsg extends DecoratedPopupPanel{
	private final static int timeOut = 5000;
	private static FlashMsg msg;
	private HTML msgHtml;
	private MsgTimer msgTimer; 
	public FlashMsg() {
		setAnimationEnabled(true);
		setWidget(msgHtml = new HTML());
		msgTimer = new MsgTimer();
		Window.addResizeHandler(new ResizeHandler() {
			
			@Override
			public void onResize(ResizeEvent event) {
				if (visible)
					setPosition();
			}
		});
	}
	private boolean visible = false; 
	public static void setMsg(TextDesc msgStr){
		init();
		msg.set(msgStr);
	}
	private static void init() {
		if (msg == null)
			msg = new FlashMsg();
	}
	private void set(TextDesc msgStr){

		if (msgStr.isHtml())
			msgHtml.setHTML(msgStr.getText());
		else 
			msgHtml.setText(msgStr.getText());
		visible = true;
		show();
		setPosition();
		msgTimer.schedule(timeOut);
	
	}
	private void add(TextDesc msgStr){
		String msg = msgHtml.getHTML();
		if (msg != null && !msg.trim().equals(""))
			msg += "<HR width='100%'/>";
		if (msgStr.isHtml())
			msg+=msgStr.getText();
		else {
			HTML h = new HTML(msgStr.getText());
			msg += h.getText();
		}
		set(new TextDesc(true, msg));
	
	}
	public static void addMsg(TextDesc msgStr){
		init();
		msg.add(msgStr);
	}
	private void setPosition() {
		DeferredCommand.addCommand(new Command() {
			
			@Override
			public void execute() {
//				if (!isShowing())
//					msgTimer.schedule(100);
//				else
				
				System.out.println("offset height: " + getOffsetHeight() );
					setPopupPosition(Window.getClientWidth() - getOffsetWidth() + Window.getScrollLeft(), Window.getClientHeight() - getOffsetHeight() + Window.getScrollTop());
			}
		});
	}
	private class MsgTimer extends Timer{

		@Override
		public void run() {
			hide();
			visible = false; 
		}
		
	} 
}
